package com.ruoyi.category.user.controller;

import com.ruoyi.category.domain.vo.NexusCategoryVo;
import com.ruoyi.category.service.INexusCategoryService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.framework.config.RedisConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 导航栏前端展示
 */

@Slf4j
@RestController
@RequestMapping("/User/NexusSphere/category")
public class NexusCategoryUserController {
    final String REDIS_KEY = "category";

    @Autowired
    private INexusCategoryService nexusCategoryService;

    @Autowired
    private RedisCache redisCache;
    @GetMapping("/list")
    public AjaxResult selectNexusCategoryVoListByParentId(Long id) {
        log.info("获取所有的分类:{}", id);
        if (id == null) {
            return AjaxResult.error("id为空");
        }
        String key = REDIS_KEY + id;
        Object cacheObject = redisCache.getCacheObject(key);
        List<NexusCategoryVo> nexusCategoryVos = null;

        if(cacheObject != null){
            log.info("redis缓存中获取数据:{}",  cacheObject);
            nexusCategoryVos = (List<NexusCategoryVo>) cacheObject;
        }else{
            log.info("redis缓存中获取数据失败，从数据库中获取数据");
            nexusCategoryVos = nexusCategoryService.selectNexusCategoryListByParentId(id);
            if (nexusCategoryVos == null || nexusCategoryVos.size() == 0) {
                return AjaxResult.error("请求数据失败，请重新尝试");
            }
            redisCache.setCacheObject(key, nexusCategoryVos);
        }
        return AjaxResult.success(nexusCategoryVos);
    }

    /**
     * 获取所有的导航栏
     * */
    @GetMapping("/nav/all")
    public AjaxResult selectCategoryNavAll(){
        List<NexusCategoryVo> nexusCategoryVoList = nexusCategoryService.selectCategoryNavAll();
        return AjaxResult.success("请求成功",nexusCategoryVoList);
    }

}
